package com.example.hrsystem;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.hrsystem.ui.attendance.AttendanceFragment;
import com.example.hrsystem.ui.home.HomeFragment;
import com.example.hrsystem.ui.user.LoginActivity;
import com.example.hrsystem.ui.user.ProfileFragment;
import com.example.hrsystem.ui.workflow.WorkflowMonitorFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    private static final String PREFS_NAME = "user_prefs";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in"; // 保持与LoginActivity一致
    private SharedPreferences sharedPreferences;
    
    private BottomNavigationView bottomNavigationView;
    private FragmentManager fragmentManager;
    private Fragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
            // 初始化SharedPreferences
            sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            
            // 检查是否已登录，如果未登录则跳转到登录页面
            if (!isUserLoggedIn()) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                return;
            }
            
            // 设置内容视图
            setContentView(R.layout.activity_main);
            
            // 初始化FragmentManager
            fragmentManager = getSupportFragmentManager();
            
            // 初始化底部导航栏
            initBottomNavigation();
            
            // 默认加载首页Fragment
            HomeFragment homeFragment = new HomeFragment();
            replaceFragment(homeFragment);
            
            Log.d("MainActivity", "首页Fragment已加载");
            
            // 设置系统UI为边缘到边缘显示
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "应用初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigation() {
        try {
            bottomNavigationView = findViewById(R.id.bottom_navigation);
            if (bottomNavigationView == null) {
                throw new NullPointerException("BottomNavigationView is null");
            }
            
            // 设置默认选中首页
            bottomNavigationView.setSelectedItemId(R.id.nav_home);
            
            bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem item) {
                    try {
                        Fragment fragment = null;
                        
                        // 根据选中的菜单项选择对应的Fragment
                        int itemId = item.getItemId();
                        if (itemId == R.id.nav_home) {
                            fragment = new HomeFragment();
                        } else if (itemId == R.id.nav_attendance) {
                            fragment = new AttendanceFragment();
                        } else if (itemId == R.id.nav_workflow) {
                            // 跳转到工作流Activity而不是直接加载Fragment
                            Intent intent = new Intent(MainActivity.this, com.example.hrsystem.workflow.ui.WorkflowActivity.class);
                            startActivity(intent);
                            return true;
                        } else if (itemId == R.id.nav_profile) {
                            fragment = new ProfileFragment();
                        }
                        
                        // 替换当前显示的Fragment
                        if (fragment != null) {
                            replaceFragment(fragment);
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "切换页面失败", Toast.LENGTH_SHORT).show();
                    }
                    
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "底部导航栏初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 替换当前显示的Fragment
     */
    private void replaceFragment(Fragment fragment) {
        try {
            Log.d("MainActivity", "replaceFragment called with: " + fragment.getClass().getSimpleName());
            
            if (fragment != null && fragmentManager != null) {
                Log.d("MainActivity", "FragmentManager is not null, creating transaction");
                
                // 检查fragment_container是否存在
                View containerView = findViewById(R.id.fragment_container);
                if (containerView == null) {
                    Log.e("MainActivity", "ERROR: fragment_container view is null!");
                    Toast.makeText(this, "容器视图未找到", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    Log.d("MainActivity", "Fragment container found successfully");
                }
                
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                Log.d("MainActivity", "Fragment transaction created");
                
                transaction.replace(R.id.fragment_container, fragment);
                Log.d("MainActivity", "Fragment replacement added to transaction");
                
                transaction.commit();
                Log.d("MainActivity", "Fragment transaction committed");
                
                currentFragment = fragment;
                Log.d("MainActivity", "Current fragment updated to: " + fragment.getClass().getSimpleName());
            } else {
                Log.e("MainActivity", "Fragment or FragmentManager is null");
                throw new NullPointerException("FragmentManager or Fragment is null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("MainActivity", "Fragment切换异常: " + e.getMessage(), e);
            Toast.makeText(this, "Fragment切换失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 检查用户是否已登录
     */
    private boolean isUserLoggedIn() {
        try {
            if (sharedPreferences == null) {
                sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            }
            boolean isLoggedIn = sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
            Log.d("MainActivity", "isUserLoggedIn: " + isLoggedIn);
            return isLoggedIn;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("MainActivity", "isUserLoggedIn error: " + e.getMessage());
            return false;
        }
    }
}